package net.chrone.quickpayapi.controller;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.chrone.quickpayapi.model.CiticWxBaseBean;
import net.chrone.quickpayapi.model.Order;
import net.chrone.quickpayapi.service.OrderService;
import net.chrone.quickpayapi.util.Constant;
import net.chrone.quickpayapi.util.Object2Xml;

@Controller
@RequestMapping("/v1.0/notify")
public class AcceptNotifyController {
	
	private  final Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private OrderService orderService;
	
	@RequestMapping("/citic")
	@Transactional(rollbackFor=Exception.class)
	public @ResponseBody String citic(@RequestBody String xml)throws IOException {
		logger.debug("wechat notify xml = " + xml);
		CiticWxBaseBean notifyBean = (CiticWxBaseBean) Object2Xml.xml2Object(xml, CiticWxBaseBean.class);
		Order orgiOrder = orderService.findByPrimaryKey(notifyBean.getOut_trade_no());
		if(null==orgiOrder){
			throw new NullPointerException("未找到交易号为:"+notifyBean.getOut_trade_no()+"的订单");
		}
		if(orgiOrder.getPaySt()!=Constant.PAY_ST_NEW){//如果订单已经成功则直接返回OK
			return "success";
		}
		int row = orderService.updateByCiticNotify(orgiOrder,notifyBean);
		if(row==1){
			return "success";
		}
		return "fail";
	}
}
